package com.simulation.aspect;

import com.simulation.controller.TestController;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Aspect//切面注解
@Component//构成
public class LoginAspect {

    private static final Logger LOG = LoggerFactory.getLogger(TestController.class);

    @Pointcut("execution(public * com.simulation.controller.*.*(..))")
    public void log(){

    }

    //前置通知
    @Before("log()")
    public void before(){
        LOG.info("方法执行");
    }

    //环绕通知
    @Around("log()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        long beginTime = System.currentTimeMillis();
        ServletRequestAttributes sra =  (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = sra.getRequest();
        //String queryString = request.getQueryString();
        //执行方法
        Object result = point.proceed();
        //执行时长(毫秒)
        LOG.info("请求地址:" + request.getRequestURL());   //url
        //LOG.info("请求参数:" + queryString);
        Enumeration<String> enu = request.getParameterNames();
        while (enu.hasMoreElements()) {
            String name = (String) enu.nextElement();
            LOG.info("请求参数name:{},value:{}", name, request.getParameter(name));
        }
        long time = System.currentTimeMillis() - beginTime;
        LOG.info("耗时:"+time); //耗时
        return result;
    }

    //异常通知
    @AfterThrowing(value = "log()",throwing = "e")
    public void afterThrowing(JoinPoint joinPoint,Exception e){
        try{
           e.printStackTrace();
        }catch (Exception e1){
            e1.printStackTrace();
        }
    }



}
